import { ref, watch, nextTick, computed } from 'vue'

export default function useFixed (props) {
  // 获取到包裹所有歌手组的ul节点
  const groupRef = ref(null)
  // 存储每组高度
  const listHeights = ref([])
  //   console.log(listHeights.value)
  // 滚动距离
  const scrollY = ref(0)
  // 当前组索引
  const currentIndex = ref(0)
  // 定义当前title与下一组title的距离
  const distance = ref(0)
  // 当前title组别
  const fixedTitle = computed(() => {
    if (scrollY.value < 0) {
      return ''
    }
    const currentGroup = props.data[currentIndex.value]
    return currentGroup ? currentGroup.title : ''
  })
  // 定义固定title栏的样式
  const fixedStyle = computed(() => {
    const distanceVal = distance.value
    // title 栏的高度为1.279rem，往上顶偏移量是负的
    const diff = distanceVal > 0 && distanceVal < 30 ? distanceVal - 30 : 0
    // console.log(diff)
    return {
      transform: `translateY(${diff}px)`
    }
  })
  // 监听data变化，一旦渲染出歌手列表就计算每组高度
  watch(
    () => props.data,
    () => {
      nextTick(() => {
        calculate()
        //   console.log(listHeights.value)
      })
    }
  )

  // 监听滚动，更新currentIndex
  watch(scrollY, (newY) => {
    const listHeightsVal = listHeights.value
    for (let i = 0; i < listHeightsVal.length - 1; i++) {
      const heightTop = listHeightsVal[i]
      const heightBottom = listHeightsVal[i + 1]
      //   console.log(heightTop, newY, heightBottom)
      //   console.log(newY >= heightTop && newY < (heightBottom - 3))
      if (newY + 8 >= heightTop && newY < heightBottom) {
        currentIndex.value = i
        // console.log(newY, currentIndex.value)s
        distance.value = heightBottom - newY
      }
    }
  })

  // 计算每组height
  function calculate () {
    // 得到所有group的list
    const list = groupRef.value.children
    const listHeightsVal = listHeights.value
    let height = 0
    listHeightsVal.length = 0
    listHeightsVal.push(height)
    for (let i = 0; i < list.length; i++) {
      height += list[i].clientHeight
      listHeightsVal.push(height)
    }
  }

  function onScroll (pos) {
    scrollY.value = -pos.y
  }
  return { groupRef, onScroll, fixedTitle, fixedStyle, currentIndex }
}
